package edu.aut.bme.hu.orkomet;

import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.soyatec.eface.core.collections.ObservableCollection;
import com.soyatec.eface.ui.RCPApplication;

import edu.aut.bme.hu.orkomet.dal.DerbyDAL;
import edu.aut.bme.hu.orkomet.engine.RDFEngine;
import edu.aut.bme.hu.orkomet.service.WsPublisher;
import edu.aut.bme.hu.orkomet.settings.Settings;
import edu.aut.bme.hu.orkomet.settings.SettingsManager;

/**
 * This class controls all aspects of the application's execution
 */
public class Application extends RCPApplication {

	private WsPublisher wspublisher= new WsPublisher();
	private Main mainWindow;
	private TableLogHandler tableLogHandler=new TableLogHandler();
	private static Settings settingsData;
	private static SettingsManager settingsManager=new SettingsManager();



	public static Settings getSettingsData() {
		return settingsData;
	}
	
	public void startPublish()
	{
		//wspublisher.start();
		wspublisher.run();
	}

	public boolean getIsPublished()
	{
		return wspublisher.isPublished();
	}
	
	public ObservableCollection<LogRecordView> getLogRecords()
	{
		return tableLogHandler.getLogRecords();
	}

	public void endPublish()
	{
		wspublisher.endPublish();
	}

	public void registerObserver(Main window)
	{
		mainWindow=window;
		notifyObservers();
	}
	
	public void initApp()
	{
		tableLogHandler.register(getClass().getPackage().getName());
		Logger.getLogger(Main.class.getName()).log(Level.INFO,"Init started");
		refreshSettings();
		RDFEngine.InitLog();
	}
	
	private void refreshSettings()
	{
		settingsData=settingsManager.loadSettings();
	}
	
	public void saveSettings(Settings data)
	{
		settingsManager.saveSettings(data);
		refreshSettings();
	}
	
	public Settings loadSettings()
	{
		return settingsManager.loadSettings();
	}
	
	public void notifyObservers()
	{
		mainWindow.refreshState();
	}

	public void exit()
	{
		try {
			wspublisher.endPublish();
			DerbyDAL.shutDownDerby();
		} catch (SQLException ex) {
			Logger.getLogger(Application.class.getName()).log(Level.SEVERE,ex.getMessage());
		}
		finally{
			shutdown();
		}
	}

	public static Application getCurrentInstance()
	{
		return (Application)(Application.getCurrent());
	}

}
